package p2pcdnsim.network;

import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;


public class RouterTable {
	private Node node;
	private Hashtable<NetworkAddress, Integer> positions;
	private Link[][] links;
	private int[][] distances;
	private int myPosition;

	public RouterTable(RouterNode node, int myPosition, Link[][] links, int[][] distances, Hashtable<NetworkAddress, Integer> positions ) {
		this.node = node;
		this.positions = positions;
		this.myPosition = myPosition;
		this.links = links;
		this.distances = distances;
	}

	public Link getLink(NetworkAddress destination) {
		return links[myPosition][positions.get(destination)];
	}
	
	public void addEntry(NetworkAddress to, Link link, int distance) {
		links[myPosition][positions.get(to)] = link;
		distances[myPosition][positions.get(to)] = distance;
	}

	
	public List<Node> getRoute(RouterNode to) {
		List<Node> route = new LinkedList<Node>();
		route.add(node);
		Node from = node;
		while(from.getNodeId() != to.getNodeId()) {
			from = from.getNetworkLayer().getRouterTable().getLink(to.getNetworkLayer().getDefaultAddress().getRouterAddress()).to;
			route.add(from);
		}
		return route;
	}

	public int getDistance(NetworkAddress destination) {
		if(links[myPosition][positions.get(destination)] == null) return 0;
		return distances[myPosition][positions.get(destination)];
	}
	
	public void printRouterEntries() {
//		for(int i=0; i<entries[myPosition].length; i++) {
//			RouterEntry e = entries[myPosition][i];
//			if(entries[myPosition][i]!=null)
//				System.out.println(e.address + " - "+ e.link.to.getNodeId());
//		}
	}
}
